package app.controllers.admin.activity;

import app.Const;
import app.kits.JobEhcacheKit;
import app.models.DaoKit;
import app.models.brand.Brand;
import app.models.activity.BrandActivity;
import app.models.activity.BrandactivityCategory;
import app.models.activity.BrandrfActivity;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.commons.lang3.BooleanUtils;
import org.joda.time.DateTime;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import java.sql.SQLException;
import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author liuhui
 * @version 1.0 2014-04-14 14:22
 * @since JDK 1.6
 */
public class BrandActivityController extends BasicController {

    public void index() {
        List<Brand> brands = Brand.dao.list();
        setAttr("brands",brands);
        render("index.ftl");
    }

    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        String name = getPara("name");
        Integer para_brand = getParaToInt("para_brand");
        Page<BrandActivity> page = BrandActivity.dao.datatable(criterias,name,para_brand);

        renderDataTables(page, criterias);
    }

    public void create() {
        BrandActivity activity = new BrandActivity();
        final DateTime now = DateTime.now();
        activity.set("begin_time", now.toDate());
        activity.set("end_time", now.plusDays(20).toDate());
        List<Brand> brandList = Brand.dao.list();//品牌
        List<BrandactivityCategory> categoryList = BrandactivityCategory.dao.list();

        setAttr("action", Const.CREATE_ACTION);
        setAttr("activity", activity);
        setAttr("brandList", brandList);
        setAttr("categoryList", categoryList);
        render("item.ftl");
    }

    public void edit() {
        BrandActivity activity = BrandActivity.dao.findById(getPara());
        List<Brand> brandList = Brand.dao.list();//品牌
        List<BrandactivityCategory> categoryList = BrandactivityCategory.dao.list();//活动分类

        String pictures = activity.getStr("picture");
        if (!Strings.isNullOrEmpty(pictures)) {
            final List<String> pics = AppFunc.COMMA_SPLITTER.splitToList(pictures);
            setAttr("pics", pics);
        }

        setAttr("action", Const.EDIT_ACTION);
        setAttr("activity", activity);
        setAttr("brandList", brandList);
        setAttr("categoryList", categoryList);
        render("item.ftl");
    }

    public void save() {
        final BrandActivity activity = getModel(BrandActivity.class, "activity");
        activity.set("reply", BooleanUtils.toBooleanObject(getPara("reply", "off")));
        String description = activity.getStr("description");
        if(!Strings.isNullOrEmpty(description)){
            description = Jsoup.clean(description, Whitelist.basicWithImages());
            activity.set("description", description);
        }
        String[] bankSels = getParaValues("bankSel"); //所选品牌

        final List<Integer> brandIds = Lists.newArrayList();
        StringBuilder sb = new StringBuilder("");

        for (String bankSel : bankSels) {
            List<String> strings = AppFunc.COMMA_SPLITTER.splitToList(bankSel);
            int id = Integer.valueOf(strings.get(0));
            String name = strings.get(1);
            brandIds.add(id);
            sb.append(name).append(",");
        }
        String brandNames = sb.substring(0, sb.length() - 1); //品牌名称
        activity.set("brand_names", brandNames);

        if (DaoKit.isNew(activity)) {
            activity.set("create_time", DateTime.now().toDate());
            activity.set("state", true);
            Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    boolean save = activity.save();
                    int id = activity.getInt("id");
                    int[] rt = saveRel(id, brandIds);
                    if (!save) {
                        return false;
                    }
                    for (int aRt : rt) {
                        if (aRt <= 0) {
                            return false;
                        }
                    }
                    return true;
                }
            });
        } else {
            final int id = activity.getInt("id");
            CacheKit.remove(JobEhcacheKit.BRAND_ACTIVITY_CACHE_NAME, JobEhcacheKit.BRAND_ACTIVITY_KEY + id);
            Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    //根据活动ID删除关联
                    boolean delBool = BrandrfActivity.dao.delByActivity(Lists.newArrayList(id + ""));
                    //更新活动
                    boolean update = activity.update();
                    //新增关联
                    int[] rt = saveRel(id, brandIds);

                    if (!delBool) {
                        return false;
                    }
                    if (!update) {
                        return false;
                    }
                    for (int aRt : rt) {
                        if (aRt <= 0) {
                            return false;
                        }
                    }
                    return true;
                }
            });
        }
        CacheKit.put(JobEhcacheKit.BRAND_ACTIVITY_CACHE_NAME, JobEhcacheKit.BRAND_ACTIVITY_KEY + activity.get(AppFunc.TABLE_PK_COLUMN), activity);
        redirect("/admin/activity/brandActivity/index");
    }

    /**
     * 保存品牌活动关联表
     *
     * @param aid      活动id
     * @param brandIds 品牌ids
     */
    private int[] saveRel(int aid, List brandIds) {
        Object[][] objects = new Object[brandIds.size()][];
        for (int i = 0; i < brandIds.size(); i++) {
            int bid = Integer.valueOf(brandIds.get(i).toString());
            Object[] obj = new Object[2];
            obj[0] = aid;
            obj[1] = bid;
            objects[i] = obj;
        }
        return Db.batch("insert into ol_brandrf_activity (activity,brand) values(?,?)", objects, 50);
    }

    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        final List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        boolean b = DaoKit.batch_remove(SqlKit.sql("brandactivity.remove"), ids);
        boolean delByActivity = BrandrfActivity.dao.delByActivity(ids);

        if (b && delByActivity) {
            for (String id : ids) {
                CacheKit.remove(JobEhcacheKit.BRAND_ACTIVITY_CACHE_NAME, JobEhcacheKit.BRAND_ACTIVITY_KEY + id);
            }
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }

    public void stop() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);

        if (DaoKit.batch_update_by_id(SqlKit.sql("brandactivity.stop"), ids)) {
            for (String id : ids) {
                CacheKit.remove(JobEhcacheKit.BRAND_ACTIVITY_CACHE_NAME, JobEhcacheKit.BRAND_ACTIVITY_KEY + id);
            }
            renderSuccess();
        } else {
            renderError("停用出现错误");
        }
    }

    public void run() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);

        if (DaoKit.batch_update_by_id(SqlKit.sql("brandactivity.run"), ids)) {
            for (String id : ids) {
                BrandActivity activity = BrandActivity.dao.findById(id);
                CacheKit.put(JobEhcacheKit.BRAND_ACTIVITY_CACHE_NAME, JobEhcacheKit.BRAND_ACTIVITY_KEY+id, activity);
            }
            renderSuccess();
        } else {
            renderError("启用出现错误");
        }
    }


}
